<?php
namespace app\index\controller;


use app\common\entity\Config;
use app\common\entity\MywalletLog;
use app\common\entity\User;
use app\common\entity\Mywallet;
use app\common\entity\UserInviteCode;
use app\common\service\Users\Service;
use app\common\shop\OrderModel;
use app\common\shop\RealNameModel;
use app\common\shop\RechargeLogModel;
use app\common\shop\UserAgentLevelModel;
use app\common\shop\UserApplyLogModel;
use app\common\shop\UserAreaLevelModel;
use app\common\shop\UserHouseLevelModel;
use app\common\shop\UserLevelModel;
use app\common\shop\UserTeamLevelModel;
use app\index\model\SendCode;
use app\index\validate\RegisterForm;
use think\Db;
use think\Request;
use think\Controller;
class Users extends Base {
    /**
     * [邀请好友图片	]
     * @param
     * @return
     */
    public function credit_qrcode( Request $request ){
        return json(['code' => 0, 'msg'=>'请求成功','info'=>Config::getValue('credit_qrcode')]);
    }
    /**
     * [会员信息]
     * @param
     * @return
     */
    public function getUser( Request $request ){
        $uid = $this->userId;
        $user = User::field('id,avatar,mobile,pid,nick_name,real_pass,wx,wx_name,wx_image_url,zfb,zfb_name,zfb_image_url,real_name,card_id,team_level,agent_level,house_level,area_level,	signbless,partner_level')
            ->where('id',$uid)
            ->find();

        $mywallet = Mywallet::getUidInfo($uid);
        $user['credit'] = $mywallet['credit'];//积分
        $user['money'] = $mywallet['money'];//余额
        $user['focas'] = $mywallet['focas'];//福卡
        $user['coupon'] = $mywallet['coupon'];//代金券
        $user['bless'] = $mywallet['bless'];//福币
        $inviteCode = new UserInviteCode();
        $invite_code = $inviteCode->getCodeByUserId($uid);
        if(empty($invite_code)){
            $inviteCode->saveCode($uid);
            $invite_code = $inviteCode->getCodeByUserId($uid);
        }


        $identity = [];
        /*$team_name = UserTeamLevelModel::where('id',$user['team_level'])->value('name');
        if($team_name)array_push($identity,'团长'.$team_name);
        $agent_name = UserAgentLevelModel::where('id',$user['agent_level'])->value('name');
        if($team_name)array_push($identity,'代理商'.$agent_name);
        $house_name = UserHouseLevelModel::where('id',$user['house_level'])->value('name');
        if($team_name)array_push($identity,$house_name);
        $area_name= UserAreaLevelModel::where('id',$user['area_level'])->value('name');
        if($team_name)array_push($identity,$area_name);
        if($user['partner_level'] == 1){
            array_push($identity,'合伙人');
        }*/
        if($user['team_level']>0){
            $identity[0] = UserTeamLevelModel::where('id',$user['team_level'])->value('name');
        }
        if($user['agent_level']>0){
            $identity[0] = UserAgentLevelModel::where('id',$user['agent_level'])->value('name');
        }
        if($user['house_level']>0){
            $identity[0] = UserHouseLevelModel::where('id',$user['house_level'])->value('name');
        }
        if($user['area_level']>0){
            $identity[1] = UserAreaLevelModel::where('id',$user['area_level'])->value('name');
        }

        $user['identity'] = $identity;

        $user['invite_code'] = $invite_code;
        $user['url'] = $request->domain().'/dist/#/login?invite_code='.$invite_code.'&active=0';
        return json(['code'=>0,'msg'=>'成功','info'=>$user]);
    }
    /**
     * [检查实名状态]
     * @return
     */
    public function checkreal(Request $request){
        $uid = $this->userId;
        //$user = User::where('id',$uid)->find();
        $info = RealnameModel::where('uid',$uid)->order('id desc')->find();
        if(empty($info)) return json(['code'=>1,'msg'=>'未实名']);
        return json(['code'=>0,'msg'=>'请求成功','info'=>$info]);
    }
    /**
     * [实名认证]
     * @param
     * @return
     */
    public function realname( Request $request ){
        $uid = $this->userId;
        $realname = $request->post('realname');// 姓名
        $card = $request->post('card');// 身份证
        if(empty($realname) || empty($card)){
            return json(['code' => 1, 'msg' => '请填写完整']);
        }
        $user = User::where('id',$uid)->find();
        if($user['real_pass'] == 2) return json(['code'=>1,'msg'=>'已经实名，不需要重复实名']);

        $info = RealnameModel::where(['uid'=>$uid,'status'=>0])->find();
        if(!empty($info)) return json(['code'=>1,'msg'=>'已提交，请等待审核']);
        $data=[
            'uid'=>$uid,
            'realname'=>$realname,
            'card'=>$card,
        ];
        RealnameModel::add($data);
        User::where('id',$uid)->setField('real_pass',3);// 待审核
        return  json(['code'=>0,'msg'=>'提交成功']);
    }

    /**
     * [绑定支付宝]
     * @return
     */
    public function bindzfb(Request $request){
        $uid = $this->userId;

        $realname = $request->post('realname');
        $zfb = $request->post('zfb');

        if(empty($realname) || empty($zfb) ) return json(['code'=>1,'msg'=>'请填写完整']);
        //$user =  User::where('id',$uid)->find();
        //if($user['isreal'] != 2) return json(['code'=>1,'msg'=>'请先实名在绑定支付宝']);
        //if($user['real_name'] != $realname) return json(['code'=>1,'msg'=>'姓名与实名不一致']);

        User::where('id',$uid)->update(['zfb'=>$zfb,'zfb_name'=>$realname]);
        return json(['code'=>0,'msg'=>'绑定成功']);
    }
    /**
     * [绑定微信]
     * @return
     */
    public function bindwx(Request $request){
        $uid = $this->userId;

        $realname = $request->post('realname');
        $wx = $request->post('wx');

        if(empty($realname) || empty($wx) ) return json(['code'=>1,'msg'=>'请填写完整']);
        //$user =  User::where('id',$uid)->find();
        //if($user['isreal'] != 2) return json(['code'=>1,'msg'=>'请先实名在绑定支付宝']);
        //if($user['real_name'] != $realname) return json(['code'=>1,'msg'=>'姓名与实名不一致']);
        User::where('id',$uid)->update(['wx'=>$wx,'wx_name'=>$realname]);
        return json(['code'=>0,'msg'=>'绑定成功']);
    }
    /**
     * [修改密码]
     * @param
     * @return
     */
    public function password( Request $request ){
        $uid = $this->userId;
        $field = $request->post('field');// 修改密码类型 password登陆密码 trad_password支付密码
        $new = $request->post('new');// 新密码
        $next = $request->post('next');// 再次密码
        if($new != $next){
            return json(['code'=>1,'msg'=>'两次密码不一致']);
        }
        if(!$field) return json(['code' => 1, 'msg' => '参数错误']);
        $mobile = $request->post('mobile');
        $code = $request->post('code');
        if(!$code) return json(['code'=>1,'msg'=>'请输入验证码']);
//        $sendCode = new SendCode($mobile, 'register');
//        if (!$sendCode->checkCode($code)) {
//            return json(['code'=>1,'msg'=>'验证码错误']);
//        }
        $form = new RegisterForm();
        if (!$form->checkChange($request->post('code'), $request->post('mobile'))) {
//            return json(['code' => 1, 'message' => '验证码输入错误']);
        }
        $user = User::where('id',$uid)->find();
        $newpass = (new Service())->getPassword($next);
        if($newpass == $user['password']){
            return json(['code'=>1,'msg'=>'新密码不能跟原密码一样']);
        }
        User::where('id',$uid)->setField($field,$newpass);
        return json(['code' => 0, 'msg' => '修改完成']);
    }

    /**
     * [我的团队]
     * @param
     * @return
     */
    public function team( Request $request ){
        $uid = $this->userId;
        $teamCount = UserLevelModel::teamCount($uid);
        $user = User::field('id,selfperformance,mathteamperformance')->where('id',$uid)->find()->toArray();
        $ztnumber = 0;
        $teamNumber = 0;
        $list = [];
        if(isset($teamCount[1])){
            $pid = $teamCount[1];// 直推会员id
            $ztnumber = count($pid);//直推人数
            $teamNumber = $teamCount['number'];// 团队人数
            $list = User::field('id,nick_name,register_time,team_level,agent_level,house_level,area_level')->where('id','in',$pid)->select()->toArray();
            foreach ($list as $key => $value) {
                $list[$key]['register_time'] = date('Y/m/d',strtotime($value['register_time']));
                $list[$key]['levelname'] = '普通会员';
                if($value['team_level'] > 0){
                    $list[$key]['levelname'] = UserTeamLevelModel::where('id',$value['team_level'])->value('name');
                }
                if($value['agent_level'] > 0){
                    $list[$key]['levelname'] = UserAgentLevelModel::where('id',$value['agent_level'])->value('name');
                }
                if($value['house_level'] > 0){
                    $list[$key]['levelname'] = UserHouseLevelModel::where('id',$value['house_level'])->value('name');
                }
                if($value['area_level'] > 0){
                    $list[$key]['levelname'] = UserAreaLevelModel::where('id',$value['area_level'])->value('name');
                }
                // 收益
                $list[$key]['money'] = MywalletLog::where('user_id',$uid)
                    ->where('from',$value['id'])
                    ->where('status',1)
                    ->sum('number');
            }
        }



        $user['ztnumber']= $ztnumber;
        $user['teamNumber'] = $teamNumber;
        $user['list'] = $list;
        $user['myreward'] = MywalletLog::where('user_id',$uid)
            ->where('types','in','4,5,9,10,12,13,14,15,17')
            ->sum('number');
        $user['houseNumber'] = MywalletLog::where('user_id',$uid)
            ->where('types',15)
            ->sum('number');
        return json(['code' => 0, 'msg'=>'请求成功','info'=>$user]);
    }

    /**
     * [个人业绩]
     * @param
     * @return
     */
    public function performancelog( Request $request ){
        $uid = $this->userId;
        $page = input('page',1);
        $limit = input('limit',10000);
        $log = OrderModel::field('id,uid,ordersn,total,paytime')
            ->where('uid',$uid)
            ->where('status','>',1)
            ->where('shoptype','<>',2)
            ->order('paytime desc')
            ->page($page,$limit)
            ->select();
        foreach ($log as $key => $value) {
            $log[$key]['paytime'] = date('Y-m-d H:i',$value['paytime']);
        }

        return json(['code' => 0, 'msg'=>'请求成功','info'=>$log]);
    }

    /**
     * [我的奖励]
     * @param
     * @return
     */
    public function myreward( Request $request ){
        $uid = $this->userId;
        /*1=> '系统充值',
            2=> '购买商品',
            3=> '取消购买',
            4=> '购物返利',
            5=> '签到',
            6=> '提现',
            7=> '会员充值',
            8=> '兑换',
            9=> '区域奖',
            10=> '直推注册',
            11=> '注册赠送',
            12=>'团队奖',
            13=>'代理游戏收益',
            14=>'游戏中红包',
            15=>'房主收益',
            16=>'奖励福卡',
            17=>'团长奖',*/
        $page = input('page',1);
        $limit = input('limit',10000);
        $log = MywalletLog::where('user_id',$uid)
            ->where('types','in','4,5,9,10,12,13,14,15,17')
            ->order('id desc')
            ->page($page,$limit)
            ->select()
            ->toArray();
        foreach ($log as $key => $value) {
            $log[$key]['create_time'] = date('Y-m-d H:i:s',$value['create_time']);
        }
        return json(['code' => 0, 'msg'=>'请求成功','info'=>$log]);
    }
    /**
     * [身份等级]
     * @param
     * @return
     */
    public function leveldata( Request $request ){
        $teamlevel = UserTeamLevelModel::field('id,name')->order('id asc')->select()->toArray();
        $agentlevel = UserAgentLevelModel::field('id,name')->order('id asc')->select()->toArray();
        $houselevel = UserHouseLevelModel::field('id,name')->order('id asc')->select()->toArray();
        $arealevel = UserAreaLevelModel::field('id,name')->order('id asc')->select()->toArray();
        $data = [
            0=>[
                'leveltype'=>1,
                'name'=>'团长',
                'level'=>$teamlevel,
            ],
            1=>[
                'leveltype'=>2,
                'name'=>'代理商',
                'level'=>$agentlevel,
            ],
            2=>[
                'leveltype'=>3,
                'name'=>'房主',
                'level'=>$houselevel,
            ],
            3=>[
                'leveltype'=>4,
                'name'=>'区域代理',
                'level'=>$arealevel,
            ],
        ];
        return json(['code' => 0, 'msg'=>'请求成功','info'=>$data]);
    }

    /**
     * [申请身份]
     * @param
     * @return
     */
    public function apply( Request $request ){
        $uid = $this->userId;
        $name = $request->post('name');
        $leveltype = $request->post('leveltype');//身份类型
        $levelid = $request->post('levelid');// 身份等级id
        if(empty($name) || empty($leveltype) ||empty($levelid) ){
            return json(['code' => 1, 'msg' => '请填写完整数据']);
        }
        $info = UserApplyLogModel::where('status',0)->where('uid',$uid)->find();
        if(!empty($info)) return json(['code' => 0, 'msg' => '请不要重复提交，已有在待审核']);
        $province = $request->post('province');// 省
        $city = $request->post('city');// 市
        $area = $request->post('area');// 区域代理
        if($leveltype == 4){
            // 区域代理只能一个
            //$user_area = User::where('area',$area)->where('area_level',$levelid)->value('id');
            $user_area = [];
            if($levelid == 1){// 区域代理
                $user_area = User::where('province',$province)->where('city',$city)->where('area',$area)->where('area_level',$levelid)->find();
            }elseif($levelid== 2){// 市代理
                $user_area = User::where('province',$province)->where('city',$city)->where('area_level',$levelid)->find();
            }
            if(!empty($user_area)){
                return json(['code' => 1, 'msg' => '该区域已经存在代理']);
            }
        }
        UserApplyLogModel::add(['uid'=>$uid,'name'=>$name,'leveltype'=>$leveltype,'levelid'=>$levelid,'area'=>$area,'province'=>$province,'city'=>$city]);
        return json(['code' => 0, 'msg' => '请求成功']);
    }
    /**
     * [申请记录]
     * @param
     * @return
     */
    public function applyLog( Request $request ){
        $uid = $this->userId;
        $page = input('page',1);
        $limit = input('limit',10000);
        $log = UserApplyLogModel::where('uid',$uid)
            ->page($page,$limit)
            ->order('id desc')
            ->select();
        $apply = new UserApplyLogModel() ;
        foreach ($log as $key => $value) {
            $log[$key]['createtime'] = date('Y-m-d H:i',$value['createtime']);
            $log[$key]['title'] = $apply->getLevelTypeName($value['leveltype']) .'-'.$apply->leveldata($value['leveltype'],$value['levelid']);
        }
        return json(['code' => 0, 'msg'=>'请求成功','info'=>$log]);
    }
    /**
     * [充值]
     * @param
     * @return
     */
    public function recharge( Request $request ){
        $uid = $this->userId;
        $sn = 'RE'.date('YmdHis',time()).mt_rand(1000,9999);
        $number = $request->post('number');
        if($number <=0) return json(['code' => 1, 'msg' => '充值数量不能小于0']);
        $paytype = $request->post('paytype');// 支付方式 1支付宝 2微信
        if(empty($paytype)) return json(['code' => 1, 'msg' => '请选择支付方式']);
        RechargeLogModel::add(['uid'=>$uid,'sn'=>$sn,'number'=>$number,'paytype'=>$paytype]);
        return json(['code' => 0, 'msg' => '请求成功']);
    }


}